package org.jradweb.core.beans;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;

public class GenericTypeAwarePropertyDescriptor  extends PropertyDescriptor {
	private final Class beanClass;

	private Class resolvedPropertyType;

	private MethodParameter writeMethodParameter;


	public GenericTypeAwarePropertyDescriptor(Class beanClass, String propertyName,
			Method readMethod, Method writeMethod, Class propertyEditorClass)
			throws IntrospectionException {

		super(propertyName, readMethod, writeMethod);
		setPropertyEditorClass(propertyEditorClass);
		this.beanClass = beanClass;
	}


	public synchronized Class getPropertyType() {
		if (this.resolvedPropertyType == null) {
			Class propertyType = super.getPropertyType();
			Method readMethod = getReadMethod();
			if (readMethod != null) {
				this.resolvedPropertyType = GenericTypeResolver.resolveReturnType(readMethod, this.beanClass);
			}
			else {
				MethodParameter writeMethodParam = getWriteMethodParameter();
				if (writeMethodParam != null) {
					this.resolvedPropertyType = writeMethodParam.getParameterType();
				}
				else {
					this.resolvedPropertyType = propertyType;
				}
			}
		}
		return this.resolvedPropertyType;
	}

	public synchronized MethodParameter getWriteMethodParameter() {
		Method writeMethod = getWriteMethod();
		if (writeMethod == null) {
			return null;
		}
		if (this.writeMethodParameter == null) {
			this.writeMethodParameter = new MethodParameter(writeMethod, 0);
			GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
		}
		return this.writeMethodParameter;
	}

}
